<template>
    <v-container fluid>
        <v-card class="elevation-10">
            <!-- 顶部操作栏 -->
            <v-card-title class="d-flex align-center pa-4">
                <div class="d-flex align-center gap-2">
                    <v-btn color="primary" prepend-icon="mdi-plus" @click="handleAdd" 
                        v-if="$perms('contract_contractinfo_insert')" 
                        >
                        Add
                    </v-btn>

                    <v-btn color="error" variant="outlined" :disabled="!selectRows.length" @click="handleDeleteBatch"
                        icon="mdi-delete" size="small" 
                        v-if="$perms('contract_contractinfo_import')"
                        />

                    <v-btn 
                        v-if="$perms('contract_contractinfo_export')" 
                        color="success"
                        variant="outlined" @click="handleExport" size="small" icon="mdi-download" />

                    <v-btn 
                        v-if="$perms('contract_contractinfo_export')"
                        color="info"
                        variant="outlined" @click="handleImport" size="small" icon="mdi-upload" />
                    <v-btn 
                        v-if="$perms('contract_contractinfo_export')"
                        color="warning"
                        variant="outlined" @click="handleDownloadTemplate" size="small" icon="mdi-file-download" />
                </div>

                <v-spacer />

                <!-- 搜索区域 -->
                <div class="d-flex align-center gap-2">
                    <v-text-field v-model="queryParams.contractId_LIKE"
                        label="合同编号" variant="outlined" density="compact" clearable hide-details
                        style="width: 150px;" class="mr-2" />
                    
                    <v-select v-model="queryParams.status_EQ"
                        :items="dict['contract_status']" item-title="dictName" item-value="dictValue"
                        label="状态" variant="outlined" density="compact" clearable hide-details
                        style="width: 120px;" class="mr-2" />

                    <v-btn variant="outlined" @click="resetQuery" class="mr-2">
                        <v-icon start>mdi-refresh</v-icon>
                        重置
                    </v-btn>

                    <v-btn color="primary" variant="flat" @click="fetchData" class="mr-2">
                        <v-icon start>mdi-magnify</v-icon>
                        搜索
                    </v-btn>

                    <v-btn variant="outlined" @click="toggleMoreQuery">
                        <v-icon start>{{ showMoreQuery ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>
                        更多
                    </v-btn>
                </div>
            </v-card-title>

            <!-- 更多查询条件 -->
            <v-expand-transition>
                <v-card-text v-show="showMoreQuery" class="pt-0">
                    <v-divider class="mb-4"></v-divider>
                    <v-row>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.signDate_BEGIN"
                                label="签约时间开始" type="date" variant="outlined" density="compact"
                                clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.signDate_END"
                                label="签约时间结束" type="date" variant="outlined" density="compact"
                                clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.paymentMethod_EQ"
                                :items="dict['payment_method']" item-title="dictName" item-value="dictValue"
                                label="付款类型" variant="outlined" density="compact" clearable
                                hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.payType_EQ"
                                :items="dict['pay_type']" item-title="dictName" item-value="dictValue"
                                label="付款方式" variant="outlined" density="compact" clearable
                                hide-details />
                        </v-col>
                    </v-row>
                </v-card-text>
            </v-expand-transition>

            <!-- 统计信息 -->
            <v-card-text class="pt-0 pb-2">
                <div class="d-flex align-center justify-space-between">
                    <div class="d-flex align-center gap-4">
                        <v-chip color="primary" variant="text">
                            <v-icon start>mdi-file-document-multiple</v-icon>
                            共 {{ total }} 个合同
                        </v-chip>
                        <v-chip v-if="selectRows.length" color="success" variant="text">
                            <v-icon start>mdi-check-circle</v-icon>
                            已选择 {{ selectRows.length }} 个
                        </v-chip>
                    </div>
                    
                    <!-- 排序选择 -->
                    <v-select
                        v-model="sortBy"
                        :items="sortOptions"
                        item-title="text"
                        item-value="value"
                        label="排序方式"
                        variant="outlined"
                        density="compact"
                        hide-details
                        style="width: 150px;"
                        @update:model-value="handleSortChange"
                    />
                </div>
            </v-card-text>

            <!-- 加载状态 -->
            <div v-if="loading" class="text-center pa-8">
                <v-progress-circular indeterminate color="primary" size="64"></v-progress-circular>
                <p class="mt-4 text-grey-darken-1">加载中...</p>
            </div>

            <!-- 空状态 -->
            <div v-else-if="!dataList.length" class="text-center pa-12">
                <v-icon size="80" color="grey-lighten-1">mdi-file-document-outline</v-icon>
                <h3 class="text-h6 mt-4 mb-2 text-grey-darken-1">暂无合同数据</h3>
                <p class="text-grey-darken-1 mb-6">请尝试调整搜索条件或添加新的合同</p>
                <v-btn color="primary" prepend-icon="mdi-plus" @click="handleAdd">
                    新增合同
                </v-btn>
            </div>

            <!-- 合同卡片列表 -->
            <v-card-text v-else class="pa-4">
                <v-row>
                    <v-col v-for="contract in dataList" :key="contract.id" cols="12" md="6" lg="4" class="mb-4">
                        <v-card 
                            class="contract-card hover-card h-100" 
                            variant="outlined" 
                            elevation="3"
                            :class="{ 'selected-card': selectRows.includes(contract.id!) }"
                        >
                            <!-- 卡片头部 -->
                            <v-card-title class="d-flex align-center justify-space-between pa-4 bg-grey-lighten-5">
                                <div class="d-flex align-center">
                                                                    <v-checkbox
                                    :model-value="selectRows.includes(contract.id!)"
                                    @update:model-value="(value: boolean) => handleToggleSelection(contract.id!, value)"
                                    hide-details
                                    density="compact"
                                    class="mr-2"
                                />
                                    <div>
                                        <div class="text-body-1 font-weight-medium text-primary">
                                            {{ contract.contractId }}
                                        </div>
                                        <div class="text-caption text-grey-darken-1">
                                            合同编号
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="d-flex align-center gap-1">
                                    <v-chip 
                                        :color="getDictColor(contract.status, 'contract_status')"
                                        size="small" 
                                        variant="elevated"
                                    >
                                        {{ getDictLabel(contract.status, 'contract_status') }}
                                    </v-chip>
                                    
                                    <v-menu>
                                        <template #activator="{ props }">
                                            <v-btn
                                                v-bind="props"
                                                icon="mdi-dots-vertical"
                                                size="small"
                                                variant="text"
                                            />
                                        </template>
                                        <v-list density="compact">
                                            <v-list-item @click="handleEdit(contract)">
                                                <template #prepend>
                                                    <v-icon>mdi-pencil</v-icon>
                                                </template>
                                                <v-list-item-title>编辑</v-list-item-title>
                                            </v-list-item>
                                            <v-list-item @click="handleDelete(contract)" class="text-error">
                                                <template #prepend>
                                                    <v-icon>mdi-delete</v-icon>
                                                </template>
                                                <v-list-item-title>删除</v-list-item-title>
                                            </v-list-item>
                                        </v-list>
                                    </v-menu>
                                </div>
                            </v-card-title>

                            <!-- 卡片内容 -->
                            <v-card-text class="pa-4">
                                <v-row dense>
                                    <!-- 金额信息 -->
                                    <v-col cols="12" class="mb-3">
                                        <div class="d-flex align-center justify-space-between">
                                            <div class="text-center">
                                                <div class="text-h6 text-success font-weight-bold">
                                                    ¥{{ formatCurrency(contract.totalAmount) }}
                                                </div>
                                                <div class="text-caption text-grey-darken-1">合同金额</div>
                                            </div>
                                            <div class="text-center">
                                                <div class="text-body-1 text-warning font-weight-medium">
                                                    ¥{{ formatCurrency(contract.discountAmount) }}
                                                </div>
                                                <div class="text-caption text-grey-darken-1">优惠金额</div>
                                            </div>
                                        </div>
                                    </v-col>

                                    <!-- 课时信息 -->
                                    <v-col cols="12" class="mb-3">
                                        <div class="d-flex align-center justify-space-between">
                                            <div class="text-center">
                                                <div class="text-body-1 font-weight-medium text-primary">
                                                    {{ contract.lessonsNumber || 0 }}
                                                </div>
                                                <div class="text-caption text-grey-darken-1">总课时</div>
                                            </div>
                                            <div class="text-center">
                                                <div class="text-body-1 font-weight-medium text-info">
                                                    {{ contract.attendedLessons || 0 }}
                                                </div>
                                                <div class="text-caption text-grey-darken-1">已上课时</div>
                                            </div>
                                            <div class="text-center">
                                                <div class="text-body-1 font-weight-medium text-success">
                                                    {{ contract.remainingLessons || 0 }}
                                                </div>
                                                <div class="text-caption text-grey-darken-1">剩余课时</div>
                                            </div>
                                        </div>
                                    </v-col>

                                    <!-- 时间信息 -->
                                    <v-col cols="12" class="mb-2">
                                        <div class="d-flex align-center mb-2">
                                            <v-icon size="16" class="mr-2 text-grey-darken-1">mdi-calendar-check</v-icon>
                                            <span class="text-caption text-grey-darken-1">签约时间：</span>
                                            <span class="text-caption">{{ formatDate(contract.signDate) }}</span>
                                        </div>
                                        <div class="d-flex align-center mb-2">
                                            <v-icon size="16" class="mr-2 text-grey-darken-1">mdi-calendar-start</v-icon>
                                            <span class="text-caption text-grey-darken-1">生效时间：</span>
                                            <span class="text-caption">{{ formatDate(contract.startDate) }}</span>
                                        </div>
                                        <div class="d-flex align-center">
                                            <v-icon size="16" class="mr-2 text-grey-darken-1">mdi-calendar-end</v-icon>
                                            <span class="text-caption text-grey-darken-1">失效时间：</span>
                                            <span class="text-caption">{{ formatDate(contract.endDate) }}</span>
                                        </div>
                                    </v-col>

                                    <!-- 付款信息 -->
                                    <v-col cols="12">
                                        <div class="d-flex align-center justify-space-between">
                                            <v-chip 
                                                :color="getDictColor(contract.paymentMethod, 'payment_method')"
                                                size="small" 
                                                variant="outlined"
                                            >
                                                {{ getDictLabel(contract.paymentMethod, 'payment_method') }}
                                            </v-chip>
                                            <v-chip 
                                                :color="getDictColor(contract.payType, 'pay_type')"
                                                size="small" 
                                                variant="outlined"
                                            >
                                                {{ getDictLabel(contract.payType, 'pay_type') }}
                                            </v-chip>
                                        </div>
                                    </v-col>
                                </v-row>
                            </v-card-text>

                            <!-- 卡片底部 -->
                            <v-card-actions class="px-4 pb-4">
                                <div class="d-flex align-center text-caption text-grey-darken-1">
                                    <v-icon size="14" class="mr-1">mdi-account</v-icon>
                                    {{ contract.createBy }}
                                </div>
                                <v-spacer />
                                <div class="text-caption text-grey-darken-1">
                                    {{ formatDate(contract.createTime) }}
                                </div>
                            </v-card-actions>
                        </v-card>
                    </v-col>
                </v-row>

                <!-- 分页 -->
                <div class="d-flex justify-center mt-6">
                    <v-pagination
                        v-model="queryParams.pageNo"
                        :length="Math.ceil(total / (queryParams.pageSize || 10))"
                        :total-visible="7"
                        @update:model-value="handlePageChange"
                    />
                </div>
            </v-card-text>
        </v-card>

        <!-- 编辑对话框 -->
        <ContractManagementEdit ref="editRef" @fetch-data="fetchData" />

        <!-- 文件上传对话框 -->
        <v-dialog v-model="importDialog" max-width="500px">
            <v-card>
                <v-card-title>导入Excel</v-card-title>
                <v-card-text>
                    <v-file-input v-model="uploadFile" label="选择Excel文件" accept=".xlsx,.xls"
                        prepend-icon="mdi-file-excel" variant="outlined" />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn color="grey-darken-1" variant="text" @click="importDialog = false">
                        取消
                    </v-btn>
                    <v-btn color="primary" variant="text" @click="confirmImport">
                        确认
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import {
    getList,
    doDelete,
    doDeleteAll,
    doExportExcel,
    doDownloadTemplate,
    doImportExcel,
    type ContractModel,
        type ContractQueryParams,
} from '@/api/contract/contractinfo/ContractManagementApi';
import ContractManagementEdit from './components/ContractManagementEdit.vue';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();

// 基础数据
const loading = ref(false);
const dataList = ref <ContractModel[]> ([]);
const total = ref(0);
const selectRows = ref<string[]>([]);
const editRef = ref();
const importDialog = ref(false);
const uploadFile = ref<File[]>([]);
const showMoreQuery = ref(false);

// 查询参数
const queryParams = reactive <ContractQueryParams> ({
    pageNo: 1,
    pageSize: 10,
    contractId_LIKE: undefined,
    courseId_EQ: undefined,
    signDate_BEGIN: undefined,
    signDate_END: undefined,
    startDate_BEGIN: undefined,
    startDate_END: undefined,
    endDate_BEGIN: undefined,
    endDate_END: undefined,
    lessonsNumber_EQ: undefined,
    status_EQ: undefined,
    paymentMethod_EQ: undefined,
    payType_EQ: undefined,
    createTime_EQ: undefined,
    createBy_EQ: undefined,
});

// 字典数据
const dict = reactive({
'contract_status': [] as any[],
'payment_method': [] as any[],
'pay_type': [] as any[],
});

// 表格列定义
const headers = computed(() => [
{
        title: '合同唯一编号',
        key: 'contractId',
        sortable: false,
    },
{
        title: '课程id',
        key: 'courseId',
        sortable: false,
    },
{
        title: '签约时间',
        key: 'signDate',
        sortable: false,
    },
{
        title: '生效时间',
        key: 'startDate',
        sortable: false,
    },
{
        title: '失效时间',
        key: 'endDate',
        sortable: false,
    },
{
        title: '合同金额',
        key: 'totalAmount',
        sortable: false,
    },
{
        title: '优惠金额',
        key: 'discountAmount',
        sortable: false,
    },
{
        title: '课时',
        key: 'lessonsNumber',
        sortable: false,
    },
{
        title: '赠送课时',
        key: 'freeLessons',
        sortable: false,
    },
{
        title: '状态',
        key: 'status',
        sortable: false,
    },
{
        title: '付款类型(一次性，分期)',
        key: 'paymentMethod',
        sortable: false,
    },
{
        title: '付款方式',
        key: 'payType',
        sortable: false,
    },
{
        title: '已上课时',
        key: 'attendedLessons',
        sortable: false,
    },
{
        title: '已排课时',
        key: 'scheduledLessons',
        sortable: false,
    },
{
        title: '​​剩余课时',
        key: 'remainingLessons',
        sortable: false,
    },
{
        title: '创建时间',
        key: 'createTime',
        sortable: false,
    },
{
        title: '创建者',
        key: 'createBy',
        sortable: false,
    },
{
        title: 'Actions',
        key: 'actions',
        sortable: false,
        width: 120,
    },
]);

// 获取数据
async function fetchData() {
    loading.value = true;
    try {
        const { data }= await getList(queryParams);
        if (data) {
            dataList.value = data.rows || [];
            total.value = data.total || 0;
        }
    } catch (error) {
        console.error('Failed to fetch data:', error);
        showError('Failed to fetch data');
    } finally {
        loading.value = false;
    }
}

// 重置查询
function resetQuery() {
    Object.assign(queryParams, {
        pageNo: 1,
        pageSize: 10,
        contractId_LIKE: undefined,
        courseId_EQ: undefined,
        signDate_BEGIN: undefined,
        signDate_END: undefined,
        startDate_BEGIN: undefined,
        startDate_END: undefined,
        endDate_BEGIN: undefined,
        endDate_END: undefined,
        lessonsNumber_EQ: undefined,
        status_EQ: undefined,
        paymentMethod_EQ: undefined,
        payType_EQ: undefined,
        createTime_EQ: undefined,
        createBy_EQ: undefined,
});
fetchData();
}

// 切换更多查询
function toggleMoreQuery() {
    showMoreQuery.value = !showMoreQuery.value;
}

// 分页处理
function handlePageChange(page: number) {
    queryParams.pageNo = page;
    fetchData();
}

function handlePageSizeChange(size: number) {
    queryParams.pageSize = size;
    queryParams.pageNo = 1;
    fetchData();
}

// 选择处理
function setSelectRows(selected: string[]) {
    selectRows.value = selected;
}

function handleToggleSelection(id: string, value: boolean) {
    if (value) {
        if (!selectRows.value.includes(id)) {
            selectRows.value.push(id);
        }
    } else {
        const index = selectRows.value.indexOf(id);
        if (index > -1) {
            selectRows.value.splice(index, 1);
        }
    }
}

// 新增
function handleAdd() {
    editRef.value?.showEdit();
}

// 编辑
function handleEdit(row: ContractModel) {
    editRef.value?.showEdit(row);
}

// 删除
async function handleDelete(row: ContractModel) {
    if (!confirm(`Are you sure to delete this record?`)) return;

    try {
        const { msg } = await doDelete({ id: row.id! });
        showSuccess(msg || 'Delete successful');
        fetchData();
    } catch (error) {
        console.error('Delete failed:', error);
        showError('Delete failed');
    }
}

// 批量删除
async function handleDeleteBatch() {
    if (!selectRows.value.length) {
        showError('Please select the data to delete');
        return;
    }

    if (!confirm(`Are you sure to delete the selected ${selectRows.value.length} records?`)) return;

    try {
        const { msg } = await doDeleteAll({ ids: selectRows.value.join(',') });
        showSuccess(msg || 'Batch delete successful');
        selectRows.value = [];
        fetchData();
    } catch (error) {
        console.error('Batch delete failed:', error);
        showError('Batch delete failed');
    }
}

// 导出Excel
async function handleExport() {
    try {
        await doExportExcel(queryParams);
        showSuccess('Export successful');
    } catch (error) {
        console.error('Export failed:', error);
        showError('Export failed');
    }
}

// 下载模板
async function handleDownloadTemplate() {
    try {
        await doDownloadTemplate();
        showSuccess('Download successful');
    } catch (error) {
        console.error('Download template failed:', error);
        showError('Download template failed');
    }
}

// 导入Excel
function handleImport() {
    importDialog.value = true;
    uploadFile.value = [];
}

async function confirmImport() {
    if (!uploadFile.value.length) {
        showError('Please select the file to upload');
        return;
    }

    const formData = new FormData();
    formData.append('file', uploadFile.value[0]);

    try {
        const response = await doImportExcel(formData);
        showSuccess(response.data?.msg || 'Import successful');
        importDialog.value = false;
        fetchData();
    } catch (error) {
        console.error('Import failed:', error);
        showError('Import failed');
    }
}

// 字典相关方法
function getDictLabel(value: any, dictType: string): string {
    const dictList = dict[dictType as keyof typeof dict] as any[];
    const item = dictList?.find(item => item.dictValue === value);
    return item?.dictName || value;
}

function getDictColor(value: any, dictType: string): string {
    // 根据字典值返回对应颜色
    const colors = ['primary', 'success', 'warning', 'error', 'info'];
    const dictList = dict[dictType as keyof typeof dict] as any[];
    const index = dictList?.findIndex(item => item.dictValue === value) || 0;
    return colors[index % colors.length];
}

// 日期格式化
function formatDate(date: string | Date | undefined): string {
    if (!date) return '';
    const d = new Date(date);
    return d.toLocaleString('zh-CN');
}

// 金额格式化
function formatCurrency(value: number | undefined): string {
    if (value === undefined || value === null) return '0.00';
    return value.toFixed(2);
}

// 排序处理
const sortBy = ref('createTime'); // 默认排序字段
const sortOptions = [
    { text: '最新创建', value: 'createTime' },
    { text: '合同金额', value: 'totalAmount' },
    { text: '课时', value: 'lessonsNumber' },
    { text: '剩余课时', value: 'remainingLessons' },
];

function handleSortChange(value: string) {
    sortBy.value = value;
    fetchData();
}

// 初始化字典数据
function initDict() {
    dict['contract_status'] = getDictListSync('contract_status') || [];
    dict['payment_method'] = getDictListSync('payment_method') || [];
    dict['pay_type'] = getDictListSync('pay_type') || [];
}

// 生命周期
onMounted(() => {
    initDict();
    fetchData();
});
</script>

<style lang="scss" scoped>
.gap-2 {
    gap: 8px;
}

.gap-1 {
    gap: 4px;
}

.contract-card {
    transition: all 0.3s ease;
    border-radius: 8px;
    overflow: hidden;

    &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }

    &.selected-card {
        border-color: var(--v-theme-primary);
        box-shadow: 0 4px 12px rgba(var(--v-theme-primary-rgb), 0.2);
    }
}

.hover-card {
    &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }
}
</style>